<template>
  <div class="baseinfo">
    <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item label="项目编号" prop="projectNo" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
            {{ form.projectNo }}
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            label="项目分类"
            prop="projectTypeSubCategory"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-select
              v-model="form.projectTypeSubCategory"
              placeholder="请选择项目分类"
              :options="projectCategoryOptions"
              :disabled="form.id != ''"
            >
              <a-icon slot="suffixIcon" type="plus" />
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            label="二级分类"
            ref="twoType"
            prop="twoType"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-select
              v-model="form.twoType"
              placeholder="请选择二级分类"
              :options="twoTypeOptions"
              @change="twoTypeChange"
            >
              <a-icon slot="suffixIcon" type="plus" />
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item
            label="是否参加五比五拼"
            ref="hasJoin"
            prop="hasJoin"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-radio-group v-model="form.hasJoin">
              <a-radio :value="true"> 是 </a-radio>
              <a-radio :value="false"> 否 </a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
        <a-col :span="8" v-if="form.hasJoin">
          <a-tooltip overlayClassName="tooltip_class">
            <template slot="title">
              ①比管理、拼效益：主要指通过精细化管理创造效益的项目（效率、质量比拼特征明显时，优先归属于比效率/比质量）<br />
              ②比技术、拼结果：主要指通过工艺技术优化创新、设备研发改造、二化等方式创造效益的项目（效率、质量比拼特征明显时，优先归属于比效率/比质量）<br />
              ③比效率、拼产出：主要指以快速交付、高效达成业务目标为主要特征的项目<br />
              ④比质量、拼精品：主要指以产品/工作质量提升为主要特征的项目<br />
              ⑤比贡献、拼业绩：除上述类别外、其他对股份集团经营目标达成贡献较大的、以经济效益为主要特征的项目，主要包括供应链挖潜、财务委挖潜及其他降本增效项目<br />
            </template>
            <a-form-model-item
              label="比拼类型"
              ref="competitionType"
              prop="competitionType"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 15 }"
            >
              <a-select
                mode="multiple"
                v-model="competitionType"
                placeholder="请选择比拼类型"
                :options="competitionTypeOptions"
                @change="competitionTypeChange"
              >
                <a-icon slot="suffixIcon" type="plus" />
              </a-select>
            </a-form-model-item>
          </a-tooltip>
        </a-col>
        <a-col :span="8" v-if="form.twoTypeName && form.twoTypeName != '其他'">
          <a-form-model-item
            label="三级分类"
            ref="threeType"
            prop="threeType"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-select
              v-model="form.threeType"
              :placeholder="form.twoType ? '请选择三级分类' : '请先选择比拼类型'"
              :options="threeTypeOptions"
              @change="threeTypeChange"
              :disabled="!form.twoType"
            >
              <a-icon slot="suffixIcon" type="plus" />
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item
            ref="projectName"
            label="项目名称"
            prop="projectName"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.projectName"
              @blur="
                () => {
                  $refs.projectName.onFieldBlur()
                }
              "
              placeholder="即“提案核心概要”"
              :disabled="form.status > 1 && !changeId"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-tooltip overlayClassName="tooltip_class">
            <template slot="title"> 如不对，请输入A级架构名称查找 </template>
            <a-form-model-item
              ref="mainDeptName"
              label="主导经营体"
              prop="mainDeptName"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 15 }"
            >
              <a-select
                :value="form.mainDeptName"
                show-search
                placeholder="输入A级组织架构名称查找"
                style="width: 100%"
                :filter-option="false"
                :not-found-content="fetching ? '找不到记录' : '找不到记录'"
                @search="fetchLandingDept"
                @change="landingDeptChange"
              >
                <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                <a-select-option v-for="(d, index) in landingDeptData" :key="index" :value="d.deptId">
                  {{ d.deptName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-tooltip>
        </a-col>
        <a-col :span="8">
          <a-form-model-item ref="landingDeptName" label="落地团队" prop="landingDeptName">
            <a-input
              v-model="form.landingDeptName"
              @blur="
                () => {
                  $refs.landingDeptName.onFieldBlur()
                }
              "
              placeholder="请输入落地团队"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8" v-if="form.hasJoin">
          <a-form-model-item
            label="是否攻克历史遗留难题或突破关键瓶颈"
            ref="hasConquer"
            prop="hasConquer"
            :label-col="{ span: 12 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-radio-group v-model="form.hasConquer">
              <a-radio :value="true"> 是 </a-radio>
              <a-radio :value="false"> 否 </a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="budgetCost"
            label="经济效益"
            prop="budgetCost"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.budgetCost"
              @blur="
                () => {
                  $refs.budgetCost.onFieldBlur()
                }
              "
              placeholder="请输入经济效益（万元）"
              type="number"
            >
              <span slot="addonAfter">万元</span>
            </a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item ref="outOpenRangeName" label="开放范围" prop="outOpenRangeName">
            <a-select
              v-model="outOpenRangeName"
              mode="multiple"
              placeholder="输入账号或者名称查找用户"
              style="width: 100%"
              :filter-option="false"
              :not-found-content="fetching ? '找不到记录' : '找不到记录'"
              @search="fetchOpenUser"
              @change="handleOpenChange"
            >
              <a-spin v-if="fetching" slot="notFoundContent" size="small" />
              <a-select-option v-for="(d, index) in userOpenData" :key="index" :value="d.username">
                {{ d.realname }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="presentSituation"
            label="现状或问题"
            prop="presentSituation"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-textarea
              v-model="form.presentSituation"
              @blur="
                () => {
                  $refs.presentSituation.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 15 }"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="improvement"
            label="改进措施"
            prop="improvement"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-textarea
              v-model="form.improvement"
              @blur="
                () => {
                  $refs.improvement.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 15 }"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="incomeMethod"
            label="收益计算方法"
            prop="incomeMethod"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-textarea
              v-model="form.incomeMethod"
              @blur="
                () => {
                  $refs.incomeMethod.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 15 }"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="accessRule"
            label="取数规则"
            prop="accessRule"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-textarea
              v-model="form.accessRule"
              @blur="
                () => {
                  $refs.accessRule.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 15 }"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
  </div>
</template>
<script>
import $ from 'jquery'
import { getAction, getActionAsync, postAction, postActionAsync } from '@/api/manage'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import Vue from 'vue'
export default {
  components: {},
  props: {
    projectBuildId: {
      Type: String,
      default: '',
    },
    selProjectType: {
      Type: String,
      default: '',
    },
    selProjectClass: {
      Type: String,
      default: '',
    },
    changeId: {
      Type: String,
      default: '',
    },
  },
  data() {
    return {
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      other: '',
      subName: '',
      form: {
        id: '',
        projectClass: '',
        projectNo: '',
        projectName: '',
        mainDeptId: '',
        mainDeptName: '',
        projectType: '',
        projectTypeSubCategory: '',
        twoType: undefined,
        twoTypeName: '',
        threeType: undefined,
        threeTypeName: '',
        competitionType: undefined,
        landingDeptName: '',
        landingDeptId: '',
        hasJoin: '',
        hasConquer: '',
        budgetCost: '',
        presentSituation: '',
        improvement: '',
        incomeMethod: '',
        accessRule: '',
        status: 0,
        additionType: '',
        openRange: '',
        openRangeName: '',
      },
      projectCategoryOptions: [],
      twoTypeOptions: [],
      threeTypeOptions: [],
      landingDeptId: undefined,
      landingDeptData: [],
      competitionTypeOptions: [],
      competitionType: undefined,
      fetching: false,
      rules: {
        projectName: [
          { required: true, message: '请输入有效的项目名', trigger: 'blur' },
          { min: 1, max: 50, message: '项目名不超过50个字符', trigger: 'blur' },
        ],
        mainDeptName: [{ required: true, message: '请输入主导经营体', trigger: 'blur' }],
        presentSituation: [
          { required: true, message: '请输入现状或问题', trigger: 'blur' },
          { min: 1, max: 2500, message: '现状或问题不超过2500个字符', trigger: 'blur' },
        ],
        improvement: [
          { required: true, message: '请输入改进措施', trigger: 'blur' },
          { min: 1, max: 2500, message: '改进措施不超过2500个字符', trigger: 'blur' },
        ],
        incomeMethod: [
          { required: true, message: '请输入收益计算方法', trigger: 'blur' },
          { min: 1, max: 2500, message: '收益计算方法不超过2500个字符', trigger: 'blur' },
        ],
        accessRule: [
          { required: true, message: '请输入取数规则', trigger: 'blur' },
          { min: 1, max: 2500, message: '取数规则不超过2500个字符', trigger: 'blur' },
        ],
        projectTypeSubCategory: [{ required: true, message: '请选择项目分类', trigger: 'change' }],
        twoType: [{ required: true, message: '请选择二级分类', trigger: 'change' }],
        threeType: [{ required: true, message: '请选择三级分类', trigger: 'change' }],
        competitionType: [{ required: true, message: '请选择比拼类型', trigger: 'change' }],
        landingDeptName: [{ required: true, message: '请输入落地团队', trigger: 'blur' }],
        hasJoin: [{ required: true, message: '请选择是否参加五比五拼', trigger: 'blur' }],
        budgetCost: [{ required: true, message: '请输入经济效益', trigger: 'blur' }],
        hasConquer: [{ required: true, message: '请选择是否攻克历史遗留难题或突破关键瓶颈', trigger: 'blur' }],
      },
      url: {
        codeInfoList: '/manage/codeInfo/list',
        getProjectByNo: '/projectBuild/getProjectByNo',
        save: '/projectBuild/add',
        queryVOById: '/projectBuild/queryVOById',
        getTeamAlevelDeptList: '/lib/hteFileClass/getTeamAlevelDeptList',
        getDeptaByUsername: '/depInfo/getDeptaByUsername',
        getUserList: '/lib/hteFileClass/getUserListOnlyUpms',
      },
      loadFinish: false,
      outOpenRangeName: undefined,
      fetching: false,
      userOpenData: [],
    }
  },
  computed: {},
  methods: {
    async doSubmit() {
      if (!this.loadFinish) {
        layer.message.warning('请等待页面加载完毕')
        return {}
      }
      var validR = false
      try {
        validR = await this.$refs.ruleForm.validate()
      } catch (e) {
        validR = false
      }
      console.log('validR', validR)
      this.form.validResult = validR
      let res = await this.doSave()
      this.projectBuildId = res
      return { valid: validR, id: res }
    },
    async doSave(dosubmit) {
      let flag = null
      var vm = this
      this.form.changeId = this.changeId
      await postActionAsync(this.url.save, this.form)
        .then((res) => {
          if (res.code == 200) {
            vm.form.id = res.result.id
            vm.form.projectNo = res.result.projectNo
            this.$message.success('保存成功')
            return (flag = res.result.id)
          } else {
            this.$message.warning('保存数据出错:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('保存数据出错:' + res.message)
        })
      return flag
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    },
    fetchOpenUser(val) {
      if (val) {
        this.userOpenData = []
        this.fetching = true
        getAction(this.url.getUserList, { name: val }).then((res) => {
          if (res.success) {
            this.userOpenData = res.result
            this.fetching = false
          }
        })
      }
    },
    handleOpenChange(value, option) {
      this.$set(this.form, 'openRange', value.join(','))
      let arr = []
      option.forEach((item) =>
        arr.push(item.componentOptions.children[0].text ? item.componentOptions.children[0].text.trim() : '')
      )
      this.$set(this.form, 'openRangeName', arr.join(','))
    },
    loadRange(nameList) {
      if (nameList) {
        this.userOpenData = []
        this.fetching = true
        getAction(this.url.getUserList, { nameList: nameList }).then((res) => {
          if (res.success) {
            this.userOpenData = res.result
            this.fetching = false
          }
        })
      }
    },
    //如果有id，则加载已填写信息
    initData() {
      if (this.projectBuildId != null && this.projectBuildId != '') {
        var vm = this
        getAction(this.url.queryVOById, { id: this.projectBuildId, changeId: this.changeId })
          .then((res) => {
            if (res.code == 200) {
              var result = res.result
              if (result != null) {
                this.form = result

                if (this.form.competitionType) {
                  this.competitionType = this.form.competitionType.split(',')
                }
                if (this.form.twoTypeName && this.form.twoTypeName != '其他') {
                  this.initThreeTypeOption(this.form.twoType)
                }

                // if (this.form.mainDeptId) {
                //   this.landingDeptId = this.form.mainDeptId.split(',')
                //   this.loadLandingDeptId(this.form.mainDeptId)
                // }
                // drcary
                if (this.form.openRange) {
                  this.outOpenRangeName = this.form.openRange.split(',')
                  this.loadRange(this.form.openRange)
                }
                this.loadFinish = true
              } else {
                vm.$message.warning('初始化项目信息为空')
              }
            } else {
              this.$message.warning('初始化项目信息失败:' + res.message)
            }
          })
          .catch((res) => {
            this.$message.warning('初始化项目信息失败:' + res.message)
          })
      } else {
        this.loadFinish = true
      }
    },
    twoTypeChange(value, option) {
      this.form.twoTypeName = option.componentOptions.children[0].text
      this.form.threeType = undefined
      this.form.threeTypeName = ''
      if (value == '2') {
        value = '1'
      }
      if(this.form.additionType != value){
        this.$info({
          title: '提示',
          content: "价值表属性更改，如果您已经保存了价值表或者核心力值表，则需要重跑试题,如果是变更过程修改该值，则需要勾选核心力值表，并点击重跑试题" ,
          onOk() {},
        });
      }
      this.form.additionType = value
      this.initThreeTypeOption(value)
    },
    threeTypeChange(value, option) {
      this.form.threeTypeName = option.componentOptions.children[0].text
    },
    competitionTypeChange(value) {
      if (value && value.length > 2) {
        this.$message.info('比拼类型选择最多两个')
        this.$set(this.form, 'competitionType', value.join(','))
        this.competitionType = value.slice(0, 2)
        return
      }
      this.$set(this.form, 'competitionType', value.join(','))
    },
    //初始化项目子类
    initProjectCategoryOptions() {
      var vm = this
      getAction(this.url.codeInfoList, { type: '项目子类', isdel: 0, parentid: vm.form.projectClass, pageSize: -1 })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              list.records.map((item) => {
                vm.projectCategoryOptions.push({ value: item.code, label: item.name })
              })
              if (vm.projectCategoryOptions.length === 1) {
                vm.form.projectTypeSubCategory = vm.projectCategoryOptions[0].value
              }
            }
          } else {
            this.$message.warning('查询项目子类失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询项目子类失败:' + res.message)
        })
    },
    initSubType() {
      var vm = this
      getAction(this.url.codeInfoList, { type: '降本增效二级分类', isdel: 0, pageSize: -1 })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              list.records.sort((a, b) => {
                return a.code - b.code
              })
              list.records.map((item) => {
                vm.twoTypeOptions.push({ value: item.code, label: item.name })
              })
            }
          } else {
            this.$message.warning('查询降本增效二级分类失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询降本增效二级分类失败:' + res.message)
        })

      getAction(this.url.codeInfoList, { type: '降本增效比拼类型', isdel: 0, pageSize: -1 })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              vm.competitionTypeOptions = []
              list.records.sort((a, b) => {
                return a.code - b.code
              })
              list.records.map((item) => {
                vm.competitionTypeOptions.push({ value: item.code, label: item.name })
              })
            }
          } else {
            this.$message.warning('查询降本增效比拼类型失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询降本增效比拼类型失败:' + res.message)
        })
    },
    initThreeTypeOption(val) {
      var vm = this
      getAction(this.url.codeInfoList, { type: '降本增效三级分类', isdel: 0, pageSize: -1, parentid: val })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              vm.threeTypeOptions = []
              list.records.sort((a, b) => {
                return a.code - b.code
              })
              list.records.map((item) => {
                vm.threeTypeOptions.push({ value: item.code, label: item.name })
              })
            }
          } else {
            this.$message.warning('查询降本增效三级分类失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询降本增效三级分类失败:' + res.message)
        })
    },
    initSubName() {
      var vm = this
      getAction(this.url.codeInfoList, {
        type: '项目子类',
        isdel: 0,
        parentid: 60,
        parentid: vm.form.projectClass,
        code: vm.form.projectType,
        pageSize: -1,
      })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              this.subName = list.records[0].name
            }
          } else {
            this.$message.warning('项目子类:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('项目子类:' + res.message)
        })
    },
    fetchLandingDept(val) {
      if (val) {
        this.landingDeptData = []
        this.fetching = true
        getAction(this.url.getTeamAlevelDeptList, { name: val }).then((res) => {
          if (res.success) {
            this.landingDeptData = res.result
            this.fetching = false
          }
        })
      }
    },
    landingDeptChange(value, option) {
      this.$set(this.form, 'mainDeptId', value)
      this.$set(this.form, 'mainDeptName', option.componentOptions.children[0].text.trim())
    },
    loadLandingDeptId(nameList) {
      if (nameList) {
        this.landingDeptData = []
        this.fetching = true
        getAction(this.url.getTeamAlevelDeptList, { nameList: nameList }).then((res) => {
          if (res.success) {
            this.landingDeptData = res.result
            this.fetching = false
          }
        })
      }
    },
    findDeptA() {
      getAction(this.url.getDeptaByUsername, { username: Vue.ls.get(USER_INFO).username }).then((res) => {
        if (res.success) {
          // this.form.mainDeptId = res.result.id ? res.result.id : Vue.ls.get(USER_INFO).deptId
          // this.form.mainDeptName = res.result.deptname ? res.result.deptname : Vue.ls.get(USER_INFO).deptName
          this.form.mainDeptId = res.result.id ? res.result.id : ''
          this.form.mainDeptName = res.result.deptname ? res.result.deptname : ''
        }
      })
    },
    mainDeptNameChange(val) {
      this.form.mainDeptId = ''
    },
  },
  mounted() {
    if (this.projectBuildId == null || this.projectBuildId == '') {
      this.form.projectClass = this.selProjectClass
      this.form.createUserName = Vue.ls.get(USER_INFO).realname
      this.findDeptA()
    }
    this.initProjectCategoryOptions()
    this.initSubType()
    this.initData()
  },
}
</script>
<style lang="less">
.tooltip_class {
  max-width: 600px !important;
}
</style>
<style lang="less" scoped>
/deep/ .ant-btn-primary {
  width: 85px;
  height: 30px;
  border-radius: 2px;
  background: #4095e4;
  margin-right: 10px;
}
/deep/ .default {
  width: 85px;
  height: 30px;
  border-radius: 2px;
}
.baseinfo {
  background-color: #fff;
  border: 1px solid #eaeaea;
  padding: 30px;
  .btn {
    display: flex;
    justify-content: center;
  }
}
</style>